package com.icare.shop.server.rest;

import com.google.common.collect.Maps;
import com.icare.shop.common.base.ResponseResult;
import com.icare.shop.server.service.DebugService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <pre>
 *    author  : tianhaibo
 *    email   : tianhaibo@jshuii.com
 *    time    : 2020/5/11   17:00
 *    desc    :
 *    version : v1.0
 * </pre>
 */
@Slf4j
@RestController
@Api(tags = "调试")
public class DebugRest {

    @Autowired
    private DebugService debugService;

    private RestTemplate restTemplate = new RestTemplate();


    @PostMapping("uploadFile")
    @ApiOperation("上传并执行")
    public ResponseResult<Object> uploadFile(@RequestParam("className")String className, @RequestParam("method")String method, @RequestParam("file") MultipartFile file){
        try {
            byte[] bytes = file.getBytes();
            return ResponseResult.success(debugService.load(className,method,bytes));
        } catch (IOException e) {
            log.error("解析文件异常",e);
        }
        return null;
    }

    @GetMapping("lock")
    @ApiOperation("加锁")
    public void lock(@RequestParam("key")String key, @RequestParam("time")Integer time){
        debugService.lock(key,time);
        return;
    }

    @GetMapping("testLock")
    @ApiOperation("测试加锁")
    public void testLock(@RequestParam("count")Integer count,@RequestParam("time")Integer time){
        Map<String, String> map = Maps.newHashMap();
        map.put("time",time+"");
        for (int i = 0;i<count;i++) {
            map.put("key",(int)(Math.random()*100000)+"");
            restTemplate.getForObject("http://192.168.91.1:20001/lock?key={key}&time={time}",String.class,map);
        }
    }
}
